package com.gwtintegration.smartrf.client;

import java.util.HashMap;
import java.util.Map;

import com.google.web.bindery.requestfactory.shared.BaseProxy;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.smartgwt.client.data.Record;

public class Converter {

	private Map<String, ProxyConverter<?>> proxyConverters;

	public Converter() {
		proxyConverters = new HashMap<String, ProxyConverter<?>>();
	}

	public <T extends BaseProxy> Record toRecord(T proxy, String proxyClassName) {

		ConverterCache converterCache = new ConverterCache();

		Record record = toRecord(proxy, proxyClassName, converterCache);

		converterCache.clear();

		return record;
	}

	@SuppressWarnings("unchecked")
	protected <T extends BaseProxy> Record toRecord(T proxy, String proxyClassName, ConverterCache converterCache) {
		ProxyConverter<T> proxyConverter = getProxyConverter(proxyClassName);
		if (proxyConverter == null) {
			throw new IllegalArgumentException("There is no ProxyConverter for " + proxyClassName);
		}

		return proxyConverter.toRecord(proxy, converterCache);
	}

	public <T extends BaseProxy> T toProxy(Record record, RequestContext requestContext, String proxyClassName) {

		ConverterCache converterCache = new ConverterCache();

		T proxy = toProxy(record, requestContext, proxyClassName, converterCache);

		converterCache.clear();

		return proxy;
	}

	@SuppressWarnings("unchecked")
	protected <T extends BaseProxy> T toProxy(Record record, RequestContext requestContext, String proxyClassName, ConverterCache converterCache) {
		ProxyConverter<T> proxyConverter = getProxyConverter(proxyClassName);

		if (proxyConverter == null) {
			throw new IllegalArgumentException("There is no ProxyConverter for " + proxyClassName);
		}

		return proxyConverter.toProxy(record, requestContext, converterCache);
	}

	protected void addProxyConverter(String proxyClassName, ProxyConverter<?> proxyConverter) {
		proxyConverters.put(proxyClassName, proxyConverter);
	}

	@SuppressWarnings("rawtypes")
	protected ProxyConverter getProxyConverter(String proxyClassName) {
		return proxyConverters.get(proxyClassName);
	}
}
